//
//  MainTabBarController.swift
//  WeiboSwift
//
//  Created by xiaokui wu on 9/9/16.
//  Copyright © 2016 wxk. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {
    
    
    // MARK: - life
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // iOS7以后设置 tintColor， 会同时修改文字和图片按照tintColor 来渲染
        tabBar.tintColor = UIColor.orangeColor()
        
        
        // addAllChildVCs()
        
        addAllChildVCsFromJson()
        
        // tabBar.addSubview(composeButton)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 避免系统的UITabBarButton盖住我们的UIButton，在viewDidLoad后再添加
        tabBar.addSubview(composeButton)
        composeButton.center = CGPointMake(tabBar.bounds.size.width * 0.5, tabBar.bounds.size.height * 0.5);
    }
    
    // MARK: - internal
    private func addAllChildVCsFromJson() {
        guard let path = NSBundle.mainBundle().pathForResource("MainVCSettings", ofType: "json")else
        {
            Log("文件不存在")
            return
        }
        
        guard let data = NSData(contentsOfFile: path) else
        {
            Log("转NSData失败")
            return
        }
        
        /*
        guard let objc = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) else
        {
            Log("转json对象失败")
            return
        }
        
        let objcArray = objc as! [[String : AnyObject]]
        for dict in objcArray {
            let title = dict["title"] as? String
            let vcName = dict["vcName"] as? String
            let imageName = dict["imageName"] as? String
            
            addChildVC(vcName, imageName: imageName, title: title)
        }
         */
        
        // try! 不放在do catch 里，不建议这样做
        // let objc = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        
        do{
            // try      正常处理异常，通过do catch来处理，try要放在do{}里面
            // try?     可能有错，也可能没错，有错会返回nil，没错会返回可选类型
            // try!     一定不会有异常，不通过do catch处理
            let objc = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
            let objcArray = objc as! [[String : AnyObject]]
            for dict in objcArray {
                let title = dict["title"] as? String
                let vcName = dict["vcName"] as? String
                let imageName = dict["imageName"] as? String
                
                addChildVC(vcName, imageName: imageName, title: title)
            }
        }catch{
            addAllChildVCs()
        }

    }
    
    private func addAllChildVCs() {
        
        addChildVC("HomeViewController", imageName: "tabbar_home",title:  "首页")
        addChildVC("MessageViewController", imageName: "tabbar_message_center",title:  "消息")
        addChildVC("DiscoverViewController", imageName: "tabbar_discover", title:  "发现")
        addChildVC("ProfileViewController", imageName: "tabbar_profile",title:  "我")
    }
    
    private func addChildVC(vcName: String?, imageName: String?, title: String?) {
        // 获取命名空间
        // guard有效解决可选绑定 嵌套过多的问题
        guard let name = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else
        {
            Log("获取命名空间失败")
            return
        }
        
        var childClass : AnyClass? = nil
        if let childVCName = vcName{
             childClass = NSClassFromString(name + "." + childVCName)
        }
    
        guard let typeCls = childClass as? UIViewController.Type else
        {
            Log("\(childClass)不能当做UIViewController")
            return
        }
        
        let vc = typeCls.init()
        
        
        if let vcImageName = imageName{
            vc.tabBarItem.image = UIImage(named: vcImageName)
            vc.tabBarItem.selectedImage = UIImage(named: vcImageName + "_highlighted")
        }
        vc.title = title
        
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    // MARK: - event
    @objc private func composeBtnClick(btn: UIButton) {
        Log("----\(btn)")
    }
    
    // MARK: - lazy
    private lazy var composeButton: UIButton = {
        () -> UIButton in // 闭包返回对应的类型
        
        let btn = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
        // 事件
        btn.addTarget(self, action: #selector(composeBtnClick), forControlEvents: .TouchUpInside)
        
        return btn
    }()// 一定要写()，代表执行闭包
    
    

}
